import {
  api,
  util,
  dialog,
  clickIncrement,
  clearIncrement
} from '../../../../js/util';
import {
  router
} from '../../../../js/router';
import {
  order,
  fee,
  grouporder,
  retreat
} from '../../../../js/modules/order';
import {
  orderPay
} from '../../../../js/modules/pay';
import {
  address
} from '../../../../js/modules/store';
import authorize from '../../../../js/modules/authorize';
import {
  annex
} from '../../../../js/modules/annex';
import {
  config
} from "../../../../js/modules/gloab";
import BasePage from '../../../../js/common/base-page'
import { getFuzzyLocation } from '../../../../js/authSetting';
import { alert, isEmpty } from '../../../../js/newUtil';
var app = getApp();
BasePage({
  pageKey:"",
  /**
   * 页面的初始数据
   */
  data: {
    imgDomain: api.imgDomain,
    enableOss: api.enableOss,
    flag: 0, //1 拼团订单 2预售订单
    groupType: 0,
    ModalType: "invo",
    Goods: [], //商品数据 
    supplier: {
      SettleType: 2,
      SupplierId: 0,
      SupplierName: ""
    }, //供应商数据 
    defaultAdr: [], //显示的地址
    consignee: {
      AddressId: 0,
      Province: '',
      City: '',
      Area: '',
      Address: '',
      Name: '',
      Mobile: ''
    },
    invoice: "<Invoice><InvType>0</InvType></Invoice>",
    invoiceInfo: {
    },
    NowInvoiceRate: 0, //当前发票税率
    invoiceRate: {
      ZZInvoiceRate: 0, //获取增值税发票税率
      PTInvoiceRate: 0, //获取普通发票税率 
      IsInvoice: false,
      FreightMode: 1, //订单运费计算模式：1标准模式  2商品指定运费模式   
    },
    InvoiceId: 0, //发票类型
    InvoiceType: 0, //发票类型
    invoiceMsg: "您已经选择不开具发票！",
    IsFreeFreight: false,
    GroupId: 0,
    GroupItemId: 0,
    ProductId: 0,
    TotalQuantity: 0,
    TotalEarnest: 0.00,
    TotalRetainage: 0.00,
    Result: "",
    Weight: 0, //重量
    Freight: 0.00, //运费
    Taxes: 0.00, //税费
    TotalAmount: 0.00, //货品总金额 
    TotalOrderAmount: 0.00, //订单总金额 
    PayTypeId: 2, //支付方式 
    PaymentId: 0,
    payData: [{
      Id: 2,
      TypeName: "在线支付"
    }],
    BuyRemark: '', //订单备注
    RemarkTips: '',
    useGrade: true,    
    //固定变量
    fixedVariable: {
      Quantity: '',
      ProductIds: '',
      ProductInfo: '',
      IsDelivery: false
    },
    isInitOrder: false,//是否初始化订单
    isSubmitOrder:false,//是否正在提交
    quantityDigits: 0,
    priceDigits: 2,//价格显示小数位数
    openDeliveryTime:false,    //开启送货时间设置
    deliveryTime:'',      //送货时间
    deliveryBeginTime:'',  //送货开始时间
    deliveryEndTime:'', //送货结束时间
    expressList:[],  //快递公司
    express:0,    //默认选中快递公司索引
    IsNecessityAddress:true, // 是否选择地址
    IsAddressToReal: false, // 收货地址验证增强，开启后需要验证地址完整性（省市区和地址详情都需要填写）
    IsEnableSelfPickup:true,//是否开启买家自提
    PickpointAddress: false, // 自提时，是否需要填写收货地址
    IsEnableLogisticsExp:true,//是否开启物流快递
    IsStoreDelivery: true, // 是否开启商家配送
    navActive: 2,
    SelfAdr:{},//自提地址
    lat:'',//维度
    lng:'',//经度
    addrNum:'',//自提id
    isIphoneX:app.globalData.isIphoneX,
    mainColor:'',//主题色
    Currency:'',//货币符号
    showReceiveType: false, // 显示切换按钮
    logisticsModeDisplayName: ['物流快递', '到店自提', '商家配送'], // 物流方式名称设置
    defaultLogisticsMode: -1, // 默认的物流方式
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var flag = options.flag;
    this.setData({
      flag: flag
    });
    this.pageKey = flag == 1 ? 'groupConfirm' : 'presellConfirm';
    this.getData(flag, options)
    this.invoiceAddCom = this.selectComponent("#invoiceAddCom");
  },
  /**
   * 获取数据
   * 将获取下单数据和配置改为promise方法并同时调用
   * @param {*} options 页面options
   */
  getData(flag, options) {
    let that = this
    Promise.all([this.initGroupOrderData(flag, options.productinfo), this.getWholesaleConfig()]).then((res) => {
      // 根据后台的默认收货方式,修改默认选中的方式
      let {
        navActive,
        defaultLogisticsMode
      } = that.data
      defaultLogisticsMode = parseInt(defaultLogisticsMode)
      if (defaultLogisticsMode != -1) {
        switch (defaultLogisticsMode) {
          case 0:
            navActive = 1 // 物流快递
            break;
          case 1:
            // 切换到自提后,需要调用获取自提点接口
            // 如果当前已经是自提则不重复调用接口
            if (navActive != 0) {
              that.bindNav({
                currentTarget: {
                  dataset: {
                    id: 0
                  }
                }
              })
            }
            navActive = 0 // 到店自提
            break;
          case 2:
            navActive = 2 // 商家配送
            break;
        }
        that.setData({
          navActive
        })
      }
    }).catch((err) => {
      console.log(err)
    })
    this.getExpress()
    this.getDefaultAddress()
  },
  //切换--自提和快递
  bindNav:function(e,callback){
    var that = this;
    var id = e.currentTarget.dataset.id;
    if(id == 0){
      getFuzzyLocation({
        type: 'gcj02', //返回可以用于wx.openLocation的经纬度
        success: function (res) {
          if (!res) return;
          console.log(res,'====getFuzzyLocation====');
          that.setData({
            lat:res.latitude,//维度
            lng:res.longitude,//经度
          })
          if(!that.data.SelfAdr.Id){
            that.getDataList();
          }
        },
        fail (err) {
          console.log('get location fail', err)
          that.setData({
            lat: 0,
            lng: 0
          })
          if(!that.data.SelfAdr.Id){
            that.getDataList()
          }
        }
      })
    }else{
      that.data.addrNum=0;
    }
    this.setData({
      navActive:id
    })
    
  },
  /*
   *加载配置项参数
   */
  getWholesaleConfig() {
    var that = this;
    var fkid = app.dns.proprietorId;
    var fkflag = app.dns.proprietor;
    return new Promise((resolve) => {
      config.getWholesaleConfigs(
        fkid,
        fkflag,
        "Wholesale",
        function (model) {
          let showReceiveType = false
          let navActive = 2
          let IsEnableLogisticsExp = model.IsEnableLogisticsExp
          let IsEnableSelfPickup = model.IsEnableSelfPickup
          let IsStoreDelivery = model.IsStoreDelivery
          let logisticsModeDisplayName = model.LogisticsModeDisplayName || ''
          logisticsModeDisplayName = logisticsModeDisplayName.split(',')
          if (IsEnableLogisticsExp) {
            navActive = 1
          } else if (IsEnableSelfPickup) {
            navActive = 0
            that.bindNav({
              currentTarget: {
                dataset: {
                  id: 0
                }
              }
            })
          } else if (IsStoreDelivery) {
            navActive = 2
          }
          if ((IsEnableLogisticsExp && IsEnableSelfPickup) || (IsEnableLogisticsExp && IsStoreDelivery) || IsStoreDelivery && IsEnableSelfPickup) {
            showReceiveType = true
          }
          that.setData({
            priceDigits: model.PriceDigits,
            quantityDigits: model.QuantityDigits,
            addressAssignDepot: model.AddressAssignDepot,
            openDeliveryTime: model.IsOpenDeliveryTime,
            IsNecessityAddress: model.IsNecessityAddress,
            IsAddressToReal: model.IsAddressToReal,
            IsEnableSelfPickup: IsEnableSelfPickup,
            PickpointAddress: model.PickpointAddress,
            IsEnableLogisticsExp: IsEnableLogisticsExp,
            IsStoreDelivery: IsStoreDelivery,
            showReceiveType,
            navActive,
            logisticsModeDisplayName
          });
          if (model.IsOpenDeliveryTime) {
            that.setDeliveryTime(model.DeliveryDeadLine);
          }
          resolve()
        });
    })
  },
  /**
   * 设置送货起始时间
   */
  setDeliveryTime:function(deadLine){
    let current = new Date();
    let miniDate = util.formatGetTime(0,'-'); 
    let hour = current.getHours(),
        minu = current.getMinutes();
    if(deadLine!=''){
      let deadTime = deadLine.split(':');
      if((hour > Number(deadTime[0])) || ((hour == Number(deadTime[0])) && (minu > Number(deadTime[1])))){
        miniDate = util.formatGetTime(1,'-');
      }
    }
    let maxDate = util.getDateSt(miniDate, -364, 'date');
    this.setData({
      deliveryBeginTime:miniDate+" "+[hour, minu].map(util.formatNumber).join(':'),
      deliveryEndTime:maxDate+" 23:59"
    })
  },
  /**
   * 改变送货时间
   */
  bindDeliveryChange:function(e){
    this.setData({
      deliveryTime:e.detail
    })
  },
  /**
   * 获取快递公司
   */
  getExpress:function(){
    let that = this;
    retreat.getLogisticsList(function (data) {
      // data.unshift({Id:0,Name:'请选择快递公司'});
      that.setData({
        expressList: data
      });
    });
    this.calFreight(this.data.consignee.AddressId);
  },
  /**
   * 改变快递公司
   */
  bindExpressChange:function(e){
    this.setData({
      express:e.detail.value
    })
    this.calFreight(this.data.consignee.AddressId);
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

    //切换收货地址后，重新计算运费
    if (this.data.consignee.AddressId > 0 && this.data.consignee.PreAddressId != this.data.consignee.AddressId) {
      this.data.consignee.PreAddressId = this.data.consignee.AddressId;
      this.setData({
        consignee: this.data.consignee
      })
      this.calFreight(this.data.consignee.AddressId);
    }
    let pages = getCurrentPages();
    let currPage = pages[pages.length - 1];
    if(currPage.data.SelfAdr){
      this.setData({
        SelfAdr: this.data.SelfAdr,
        addrNum:this.data.SelfAdr.Id
      });
    }
    this.setData({
      mainColor:api.titleColor||"#e56b14",
      Currency:api.Currency || '￥'
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    clearIncrement();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  /**默认地址加载 */
  getDefaultAddress() {
    var that = this;
    var adrId = that.data.consignee.AddressId;
    if (adrId == 0) {
      address.getDefaultAddress(function(ads) {
        if (ads!=undefined&&Object.keys(ads).length>0) {
          var consignee = {
            AddressId: ads.Id,
            Province: ads.Province,
            City: ads.City,
            Area: ads.Area,
            Address: ads.Address,
            Name: ads.Name,
            Mobile: ads.Mobile
          }
          that.setData({
            defaultAdr: ads,
            consignee: consignee
          });
        }
      });
    }
  },

  /**初始化发票信息 */
  initInvoiceInfo() {
    var that = this;
    fee.initInvoiceInfo(function(res) {
      if (res) {
        var nowInvoiceRate = 0;
        if (res.InvoiceType == 1) {
          nowInvoiceRate = res.invoiceRate.PTInvoiceRate;
        } else if (res.InvoiceType == 2) {
          nowInvoiceRate = res.invoiceRate.ZZInvoiceRate;
        }
        that.setData({
          InvoiceId: res.InvoiceId,
          InvoiceType: res.InvoiceType,
          invoiceMsg: res.invoiceMsg,
          invoiceInfo: res.invoiceInfo,
          invoiceRate: res.invoiceRate,
          NowInvoiceRate: nowInvoiceRate
        });
        that.invoiceAddCom.initInvoice(res.invoiceInfo, res.InvoiceType);
      }
      that.calInvRate();
      that.initFreightMode(that);
    });
  },
  /**
   * 初始化运费模式
   */
  initFreightMode(that) {
    annex.isFreeFreight(function (res) {
      if (res.Success && Number(res.Content) > 0) {
        that.setData({
          IsFreeFreight:true,
          Freight:0,
          invoiceRate: that.data.invoiceRate
        })
      }
      //计算运费
      that.calFreight(that.data.consignee.AddressId);
    });
  },
  /**
   * 选择支付方式
   */
  chosePayWay: function(event) {
    this.setData({
      PayTypeId: event.currentTarget.dataset.val
    })
  },

  /**
   * 提交订单
   */
  submitGroupOrder: function() {
    var that = this;
    let navActive = this.data.navActive
    let PickpointAddress = this.data.PickpointAddress
    if (that.data.isInitOrder) return;
    if (navActive == 1 || navActive == 2 || PickpointAddress) {
      if (that.data.IsNecessityAddress){
        if(that.data.consignee.AddressId==0 && that.data.IsEnableLogisticsExp){
          util.tips("请选择收货地址");
          return;
        }
      }
      if (that.data.IsAddressToReal) { // 校验地址完整性
        let consignee = that.data.consignee || {}
        if (isEmpty(consignee.Province) || isEmpty(consignee.City) || isEmpty(consignee.Area) || isEmpty(consignee.Address)) {
          // 如果没有省市区和详细地址，则阻止提交
          alert('请完善收货地址')
          return
        }
      }
    }
    if(navActive == 1){
      if(!that.data.expressList[that.data.express].Id && that.data.IsEnableLogisticsExp){
        util.tips("平台尚未配置快递公司，请联系管理员进行处理");
        return;
      }
    }else if (navActive == 0) {
      if(!that.data.addrNum){
        util.tips("请选择自提点");
        return;
      }
    }
    clickIncrement(function() {
      if (that.data.isSubmitOrder) return;
      that.data.isSubmitOrder = true;
      that.setData({
        isSubmitOrder: that.data.isSubmitOrder
      })
      var flag = that.data.flag;
      // console.log(that.data.consignee,'======that.data.consignee');
      var param = {
          Flag: flag,
          GroupId: that.data.GroupId,
          GroupItemId: that.data.GroupItemId,
          ProductId: that.data.ProductId,
          Earnest: that.data.TotalEarnest,
          TotalAmount: that.data.TotalAmount,
          TotalOrderAmount: that.data.TotalOrderAmount,
          Taxes: that.data.Taxes,
          Freight: that.data.Freight,
          FreeFreight: that.data.IsFreeFreight,
          TotalWeight: that.data.TotalWeight || 0,
          consignee: that.data.consignee,
          //AddressProvince: this.data.consignee.Province,
          PayTypeId: that.data.PayTypeId,
          PaymentId: that.data.PaymentId,
          InvoiceId: that.data.InvoiceId,
          InvoiceType: that.data.InvoiceType,
          BuyRemark: that.data.BuyRemark,
          Goods: that.data.Goods,
          invoice: that.data.invoice,
          supplier: that.data.supplier,
          // DeliveryId: that.data.expressList[that.data.express].Id,
          DeliveryId:that.data.navActive == 1 ? (that.data.IsEnableLogisticsExp?that.data.expressList[that.data.express].Id:0) : 0,
          DeliveryTime: that.data.deliveryTime,
          PickPointId: that.data.navActive == 0 ? that.data.addrNum : 0,
          IsDelivery: (navActive == 1 && that.data.IsEnableLogisticsExp) ?  1 : 0,
          LogisticsMode: navActive == 2 ? 2 : (navActive == 1 ? 0 : 1)
        }
      // console.log(param,'=======1');
      // 自提时，并且没有开启 自提需要收货地址，那么不传地址信息
      if (navActive == 0 && !PickpointAddress) {
        param.consignee = {}
        param.consignee.AddressId = 0
        param.needNotConsignee = true
      }
      var xmlAary = grouporder.packOrderInfo(param)
      grouporder.submitGroupOrder(xmlAary, function(res) {        
        var result = res.Result;
        if (result == "Limit") {
          util.tips("提交失败");
          router.navigate({
            path: "groupList",
            params: {
              flag: flag
            }
          });
          that.setData({
            isSubmitOrder: false
          });  
        } else if (result == "OK") {
          //跳转到收银台页面 
          orderPay.findPayOrderData(res.Content, "cashier",function(recordToken){
            router.redirect({
              path: 'cashier',
              params: {
                paytoken: recordToken,
                pagetype: 'order'
              }
            });
          },false);
          that.setData({
            isSubmitOrder: false
          });   

        } else {
          util.tips(res.Content);
          that.setData({
            isSubmitOrder: false
          });  
        }
      });
    });
  },
  /**
   * 切换发票
   */
  onSwitchInvoiceEvent(evt) {
    let invoiceType = parseInt(evt.currentTarget.dataset.val);
    let nowInvoiceRate = 0;
    switch (invoiceType) {
      case 0:
        this.data.invoice = "<Invoice><InvType>0</InvType></Invoice>";
        break;
      case 1:
        nowInvoiceRate = this.data.invoiceRate.PTInvoiceRate;
        break;
      case 2:
        nowInvoiceRate = this.data.invoiceRate.ZZInvoiceRate;
        break;
    }
    this.setData({
      InvoiceType: invoiceType,
      NowInvoiceRate: nowInvoiceRate,
      invoice: this.data.invoice
    }, () => {
      if (invoiceType == 0) {
        this.calInvRate();
      }
      else{
        this.invoiceAddCom.onSwitchInvoiceEvent(invoiceType);
      }
    });
   
  },
  /**发票回调 */
  onInvoiceCallbackEvent(e) {
    this.setData(e.detail.content, () => {
      this.calInvRate();
    })
  },
  
  /**
   * 地址选择
   */
  goAddr: function() {
    router.navigate({
      path: "addressList",
      params: {
        id: this.data.consignee.AddressId
      }
    });
  },
  /**
   * 自提选择
   */
  bindAddr:function(e){
    router.navigate({
      path: "selfList",
      params: {
        id: e.currentTarget.dataset.id,
        lng: this.data.lng,
        lat: this.data.lat
      }
    });
  },
  calFreight(addressId) {
    let that = this;
    // var orderInfo = that.data.spOder;
    let { Weight,Freight,Taxes,TotalAmount,TotalEarnest,TotalQuantity}=this.data;
    
    //计算订单除运费税费外的总金额
    var calcuData = {
      Freight: Freight, //运费
      Taxes: Taxes, //税费
      ProductAmount: TotalAmount, //货品总金额 
      TotalEarnest: TotalEarnest //定金
    }
    var fees = grouporder.calGroupPayables(calcuData,true);
    // console.log(that.data.expressList,that.data.express,'====');
    let param = {
      Weight: Weight,
      Price: fees.payables,
      AddressId: addressId,
      DeliveryId:that.data.navActive == 1 ? (that.data.IsEnableLogisticsExp?that.data.expressList.length==0?0:that.data.expressList[that.data.express].Id:0) : 0,
      BuyCount:TotalQuantity,
      FreightAmount:fees.payables,
      FreightMode: that.data.invoiceRate.FreightMode,
      FreeFreight: that.data.IsFreeFreight,
      flag:0
    };

    fee.calFreight(param, function (freight) {
      that.setData({
        Freight: that.data.IsEnableLogisticsExp?parseFloat(freight):0.00
      });
      that.setPayables();
    });

  },
  /**计算税费 */
  calInvRate() {
    var param = {
      ProductAmount: this.data.TotalAmount,
      NowInvoiceRate: this.data.NowInvoiceRate,
      CouponDiscount: 0,
      DeductionTotal: 0
    };
    var taxes = fee.calInvRate(param);
    this.setData({
      Taxes: taxes
    });
    this.setPayables();
  },
  
  /**
   * 点击留言
   */
  showMsgModal(evt) {
    this.setData({
      ModalType: 'msg',
      RemarkTips: this.data.BuyRemark
    });
    dialog.showModal(this, 'showModalStatus')
  },
  /**隐藏多规格层 */
  hideModal() {
    var that = this;
    dialog.hideModal(that, 'showModalStatus')
  },

  /**订单备注 */
  BuyRemarkInput(e) {
    var value = e.detail.value;
    var len = parseInt(value.length);
    if (len > this.data.max) return;
    this.setData({
      currentWordNumber: len,
      RemarkTips: e.detail.value
    });
  },
  /**
   * 确认输入
   */
  onComfirmRemark(e) {
    this.setData({
      BuyRemark: this.data.RemarkTips
    });
    this.hideModal();
  },

  /**计算订单价格 */
  setPayables() {
    var param = {
      Freight: this.data.Freight, //运费
      Taxes: this.data.Taxes, //税费
      ProductAmount: this.data.TotalAmount, //货品总金额 
      TotalEarnest: this.data.TotalEarnest //定金
    }
    var fees = grouporder.calGroupPayables(param);
    this.setData({
      TotalOrderAmount: fees.payables,
      TotalRetainage: fees.retainage
    });
  },

  /**加载订单初始化信息 */
  initGroupOrderData(flag, productInfo) {
    var that = this;
    wx.showLoading({
      title: '加载中'
    });
    that.setData({
      isInitOrder: true
    });
    return new Promise((resolve) => {
      grouporder.initGroupOrderConfirmData(productInfo, function (status, res) {
        wx.hideLoading();
        if (!status) {
          that.setData({
            isInitOrder: false
          });
          util.confirm(function () {
            router.navigateBack();
          }, function () {}, "结算失败：" + res, "温馨提示");
          resolve()
          return;
        }
        //供应商数据
        var supplier = {
          SettleType: res.SettleType,
          SupplierId: res.SupplierId,
          SupplierName: res.SupplierName
        }
        that.setData({
          isInitOrder: false,
          Goods: res.Goods,
          groupType: res.GroupType,
          TotalAmount: res.TotalAmount,
          Weight: res.TotalWeight,
          TotalOrderAmount: res.TotalOrderAmount,
          Freight: res.Freight,
          IsFreeFreight: res.IsFreeFreight == true || res.IsFreeFreight == "true" ? true : false,
          GroupId: res.GroupId,
          GroupItemId: res.GroupItemId,
          ProductId: res.ProductId,
          TotalQuantity: res.TotalQuantity,
          TotalEarnest: res.TotalEarnest,
          TotalRetainage: res.TotalRetainage,
          Result: res.Result,
          supplier: supplier,
          defaultLogisticsMode: res.LogisticsMode
        });
        //加载发票信息
        that.initInvoiceInfo();
        resolve()
      });
    })
  },
  /**
   * 进入商品清单
   */
  goGoodsList:function(){
    router.navigate({
      path:'orderGoodsList',
      params:{}
    })
  },
  // 自提
  getDataList:function(){
    var that = this;
    var data = {lng:this.data.lng,lat:this.data.lat,PageIndex:1,PageSize:1};
    address.selfAddressList(data,function(content){
      if (content.Success) {
        var data = content.Content.data;
        if (data.length > 0) {
          if (data[0].distance > 1000) {
            data[0].distance = (data[0].distance / 1000) + 'km'
          } else if (data[0].distance >= 0) {
            data[0].distance = data[0].distance + 'm'
          } else {
            data[0].distance = '0m'
          }
          that.setData({
            SelfAdr: data[0],
            addrNum: data[0].Id
          })
        } else {
          util.tips("附近没有可选自提点噢！");
        }
      } else {
        util.tips("附近没有可选自提点噢！");
      }
    })
  },
})